package com.windoent.yugioh.ui.fragment.saishi.baoming;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.windoent.yugioh.MyApplication;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.banner.ImageAdapter;
import com.windoent.yugioh.adapter.brvah.multi.JoinGamePlayersMultiAdapter;
import com.windoent.yugioh.base.BaseFragment;
import com.windoent.yugioh.bean.GameStatusRoleBean;
import com.windoent.yugioh.bean.GeneralBean;
import com.windoent.yugioh.bean.JingWeiBean;
import com.windoent.yugioh.bean.JoinPlayerBean;
import com.windoent.yugioh.bean.SaiShiDetailsBean;
import com.windoent.yugioh.bean.UserBean;
import com.windoent.yugioh.bean.UserGameList;
import com.windoent.yugioh.bean.eventbus.FragmentActivityMessageEvent;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.help.AndroidScheduler;
import com.windoent.yugioh.help.map.OpenMapUtil;
import com.windoent.yugioh.help.recycle.GridSpaceItemDecoration;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.ui.activity.meinfo.RealNameAuthActivity;
import com.windoent.yugioh.ui.activity.saishi.ConTestationListActivivty;
import com.windoent.yugioh.ui.activity.saishi.ZhiFuActivity;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.NotificationsUtils;
import com.windoent.yugioh.utils.PermissionTool;
import com.windoent.yugioh.utils.SimpleUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.dialog.CanSaiBaoMingDetailsDialog;
import com.windoent.yugioh.widget.dialog.CanSaiBaoMingXunHuiDetailsDialog;
import com.windoent.yugioh.widget.dialog.ExitGameReasonDialog;
import com.windoent.yugioh.widget.dialog.NotificationOpenDialog;
import com.windoent.yugioh.widget.dialog.PictureVerifyDialog;
import com.windoent.yugioh.widget.dialog.SucessFailAutoDismissDialog;
import com.windoent.yugioh.widget.dialog.SureNotDialog;
import com.youth.banner.Banner;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/5/17 14:14
 * desc   :报名详情
 */
public class BaoMingDetailsFragment extends BaseFragment {
    private TextView mBtnGetCode;
    private LinearLayout mLlGetCode;
    private TextView mTvStatusLeft;
    private TextView mTvStatusLeftKuohao;
    private TextView mTvStatusRiht;

    private TextView mTvLocationName;
    private TextView mTvDetailTime;
    private TextView mTvDianpu;
    private RecyclerView mRecyclerView;
    private Banner mBanner;
    private ImageAdapter bannerAdapter;
    private TextView mTvFormat;
    private TextView mTvCost;
    private TextView mTvPrize;
    private TextView mTvTellphone;
    private TextView mTvRemark;
    private SmartRefreshLayout mSmartLayout;
    private TextView mTvHuanjing;
    private TextView mTvSaizhi;
    private RelativeLayout mRlRv;

    private SaiShiDetailsBean.DataBean.InfoBean info;
    private String id = "";
    private boolean signup = false;//选手是否包名
    private int status;//1审核中2报名中3开始比赛4开始瑞士轮5开启淘汰赛
    private String role = "";
    private JoinGamePlayersMultiAdapter adapter;
    private int isOnlinePayment;
    private SaiShiDetailsBean.BottomBean bottom;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_saishi_baoming_details;
    }

    @Override
    protected void initEventAndData() {
        initView();
        initData();
        initListener();
    }

    private void initListener() {
        mRlRv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, ConTestationListActivivty.class);
                intent.putExtra("id", id);
                startActivity(intent);
            }
        });
        mLlGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String string = MyApplication.getInstance().getUserInfo();
                if (BaseMethod.notNull(string) && BaseUtils.isJSONValid(string)) {
                    UserBean userBean = gson.fromJson(string, UserBean.class);
                    boolean real = userBean.isReal();
                    if (!real) {//实名
                        showShiMinngDialog();
                    } else {
                        bottnBottomClick();
                    }
                }
            }
        });
        mTvLocationName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (info != null) {
                    SaiShiDetailsBean.DataBean.InfoBean.BasicInfoBean basic_info = info.getBasic_info();
                    if (basic_info != null && getActivity() != null) {
                        String address_position = basic_info.getAddress_position();
                        if (BaseUtils.isJSONValid(address_position)) {
                            JingWeiBean json = gson.fromJson(address_position, JingWeiBean.class);
                            if (json != null && BaseMethod.notNull(json.getLatitude()) && BaseMethod.notNull(json.getLongitude())) {
                                OpenMapUtil.openMapPopupWindow(getActivity(), mTvLocationName, basic_info.getAddress(), BaseUtils.stringToDouble(json.getLatitude()), BaseUtils.stringToDouble(json.getLongitude()));
                            } else
                                ToastUtils.showText(getString(R.string.string_latitude_logtitude_no_data));
                        } else
                            ToastUtils.showText(getString(R.string.string_latitude_logtitude_no_data));
                    } else
                        ToastUtils.showText(getString(R.string.string_latitude_logtitude_no_data));
                } else ToastUtils.showText(getString(R.string.string_latitude_logtitude_no_data));
            }
        });
    }

    //底部按钮事件
    private void bottnBottomClick() {
        if (bottom != null && bottom.getType() == 3 && (bottom.getAction() == 1 || bottom.getAction() == 2)) {
            //1：支付动作 2：预约动作
            if (bottom.getAction() == 1) {
                //1：支付动作
                //参赛交钱
                showXunHuiDialog();
            } else {
                //2：预约动作
                showSureYuYueDialog(id);
            }
        } else if (info != null) {
            /**
             * "customer":"商家",
             * "customerReferee":"商家+主裁判",
             * "notJoin":"没有参加",
             * "pReferee":"主裁判",
             * "player":"选手",
             * "referee":"裁判",
             * "visitor":"游客"
             */
            boolean notJoin = BaseMethod.notNull(role) && role.equals("notJoin");
            boolean pReferee = BaseMethod.notNull(role) && role.equals("pReferee");
            boolean player = BaseMethod.notNull(role) && role.equals("player");
            boolean referee = BaseMethod.notNull(role) && role.equals("referee");
            boolean customer = BaseMethod.notNull(role) && role.equals("customer");
            boolean customerReferee = BaseMethod.notNull(role) && role.equals("customerReferee");
            boolean pending = BaseMethod.notNull(role) && role.equals("pending");
            if (notJoin) {
                if (isOnlinePayment == 1) {
                    //参赛交钱
                    showXunHuiDialog();
                } else {
                    showDetailsDialog(info);//参加比赛
                }
            } else if (player) {
                if (signup) {//选手退出
                    if (isOnlinePayment == 1) {
                        //退赛退钱
                    } else
                        existDialog();
                } else {
                    showDetailsDialog(info);//选手参加比赛
                }
            } else if (customer || customerReferee) {
                if (status == 2) {
                    //开启比赛(店家)
                    dianjiaStartGame(id);
                } else if (status == 1) {
                    ToastUtils.showText(getString(R.string.string_nt_immediately_start));
                } else {
                    ToastUtils.showText(getString(R.string.string_already_start));
                }
            }
        }
    }

    //预约比赛
    private void showSureYuYueDialog(String id) {
        SureNotDialog dialog = new SureNotDialog(mContext);
        dialog.setYesStr(getString(R.string.string_yuyue_warning));
        dialog.setNoStr(getString(R.string.dl_cancel));
        dialog.setTvContent(getString(R.string.string_if_yuyue_warn));
        dialog.setYesOnclickListener(new SureNotDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                saishiYuYue(id);
            }
        });
        dialog.show();
    }

    //赛事预约
    private void saishiYuYue(String id) {
        showLoadingDialog("");
        PhoneLive.saishiYuYue(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int idres) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    GeneralBean fromJson = gson.fromJson(response, GeneralBean.class);
                    if (fromJson != null) {
                        int code = fromJson.getCode();
                        String msg = fromJson.getMsg();
                        if (code == 200) {
                            BaseMethod.showSucessDialog(mContext, BaseMethod.notNullDefaultValue(msg, getString(R.string.string_yuyue_sucess)), new SucessFailAutoDismissDialog.OnInterface() {
                                @Override
                                public void onDissmiss() {
                                    fresh(id);
                                }
                            });
                        } else {
                            BaseMethod.showFailDialog(mContext, getString(R.string.string_yuyue_fail), BaseMethod.notNullDefaultValueNull(msg));
                        }
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //取消参赛
    private void existDialog() {
        ExitGameReasonDialog dialog = new ExitGameReasonDialog(mContext);
        dialog.setOnclickListener(new ExitGameReasonDialog.onClickListener() {
            @Override
            public void onClick(String string) {
                exitGamePlayers(string);
            }
        });
        dialog.show();
    }

    //选手退出参赛
    private void exitGamePlayers(String string) {
        showLoadingDialog("");
        PhoneLive.exitGamePlayers(getUserToken(), id, string, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int idres) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    GeneralBean fromJson = gson.fromJson(response, GeneralBean.class);
                    if (fromJson != null) {
                        int code = fromJson.getCode();
                        String msg = fromJson.getMsg();
                        if (code == 200) {
                            fresh(id);
                            BaseMethod.showSucessDialog(mContext, BaseMethod.notNullDefaultValue(msg, getString(R.string.string_exit_judge_game)), null);
                        } else {
                            BaseMethod.showFailDialog(mContext, getString(R.string.string_caipan_exit_fail), msg);
                        }
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //店家开启比赛
    private void dianjiaStartGame(String id) {
        showLoadingDialog("");
        PhoneLive.dianjiaStartGame(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int idre) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    GeneralBean fromJson = gson.fromJson(response, GeneralBean.class);
                    if (fromJson != null) {
                        if (fromJson.getCode() == 200) {
                            BaseMethod.showSucessDialog(mContext, BaseMethod.notNullDefaultValue(fromJson.getMsg(), getString(R.string.string_start_game_sucess)), new SucessFailAutoDismissDialog.OnInterface() {
                                @Override
                                public void onDissmiss() {
                                    fresh(id);
                                    //没有通知权限，跳转设置打开
                                    if (!NotificationsUtils.isNotificationEnabled(mContext))
                                        showNotificationDialog();
                                }
                            });
                        } else {
                            String msg = fromJson.getMsg();
                            BaseMethod.showFailDialog(mContext, getString(R.string.string_start_game_fail), msg);
                        }
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //巡回赛显示
    private void showXunHuiDialog() {
        CanSaiBaoMingXunHuiDetailsDialog dialog = new CanSaiBaoMingXunHuiDetailsDialog(mContext);
        dialog.setType("4");
        dialog.setYesOnclickListener(new CanSaiBaoMingXunHuiDetailsDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                showPicVerfyDialog();
            }
        });
        dialog.show();
    }

    //图片滑动验证
    private void showPicVerfyDialog() {
        PictureVerifyDialog dialog = new PictureVerifyDialog(mContext);
        dialog.setOnclickListener(new PictureVerifyDialog.onClickListener() {
            @Override
            public void onClick() {
                startActivityForResult(new Intent(mContext, ZhiFuActivity.class), Constants.ZHIFUREQUEST);
            }
        });
        dialog.show();
    }

    //实名认证
    private void showShiMinngDialog() {
        SureNotDialog dialog = new SureNotDialog(mContext);
        dialog.setTvContent(getString(R.string.string_no_shiming_warn));
        dialog.setNoStr(getString(R.string.dl_cancel));
        dialog.setYesStr(getString(R.string.string_to_shiming_renzhen));
        dialog.setYesOnclickListener(new SureNotDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                //yes
                Intent intent = new Intent(mContext, RealNameAuthActivity.class);
                intent.putExtra("baoming_details", 1);
                startActivityForResult(intent, Constants.BAOMING_DETAILS);
            }
        });
        dialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.BAOMING_DETAILS && resultCode == Activity.RESULT_OK) {
            bottnBottomClick();
        } else if (requestCode == Constants.ZHIFUREQUEST && requestCode == Activity.RESULT_OK) {
            BaseMethod.showSucessDialog(mContext, getString(R.string.string_baoming_sucess), new SucessFailAutoDismissDialog.OnInterface() {
                @Override
                public void onDissmiss() {
                    //没有通知权限，跳转设置打开
                    if (!NotificationsUtils.isNotificationEnabled(mContext))
                        showNotificationDialog();
                }
            });
        }
    }

    //参赛报名
    private void showDetailsDialog(SaiShiDetailsBean.DataBean.InfoBean info) {
        CanSaiBaoMingDetailsDialog dialog = new CanSaiBaoMingDetailsDialog(mContext);
        dialog.setYesOnclickListener(new CanSaiBaoMingDetailsDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                applaySaiShiGame();
            }
        });
        SaiShiDetailsBean.DataBean.InfoBean.BasicInfoBean basic_info = info.getBasic_info();
        SaiShiDetailsBean.DataBean.InfoBean.DescInfoBean desc_info = info.getDesc_info();
        if (basic_info != null) {
            dialog.setTitle(basic_info.getName());
            dialog.setTimeStr(basic_info.getStart_at());
        }
        if (desc_info != null) {
            dialog.setCostStr(desc_info.getCost() + "");
            dialog.setPhoneStr(desc_info.getContact());
        }
        dialog.show();
    }

    //选手申请比赛
    private void applaySaiShiGame() {
        showLoadingDialog("");
        PhoneLive.applaySaiShiGame(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id1) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    GeneralBean fromJson = gson.fromJson(response, GeneralBean.class);
                    if (fromJson != null) {
                        String msg = fromJson.getMsg();
                        if (fromJson.getCode() == 200) {
                            fresh(id);
                            BaseMethod.showSucessDialog(mContext, BaseMethod.notNullDefaultValue(msg, getString(R.string.string_baoming_sucess)), new SucessFailAutoDismissDialog.OnInterface() {
                                @Override
                                public void onDissmiss() {
                                    //没有通知权限，跳转设置打开
                                    if (!NotificationsUtils.isNotificationEnabled(mContext))
                                        showNotificationDialog();
                                }
                            });
                        } else {
                            BaseMethod.showFailDialog(mContext, getString(R.string.string_baoming_fail), msg);
                        }
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //权限通知对话框
    private void showNotificationDialog() {
        NotificationOpenDialog dialog = new NotificationOpenDialog(mContext);
        dialog.setOnclickListener(new NotificationOpenDialog.onClickListener() {
            @Override
            public void onClick() {
                PermissionTool.requestNotify(mContext);
            }
        });
        dialog.show();
    }

    private void initData() {
        initAdapter();
        initBanner();
    }


    private void initBanner() {
        bannerAdapter = new ImageAdapter(null);
        mBanner.setAdapter(bannerAdapter);
    }

    private void initAdapter() {
        GridLayoutManager manager = new GridLayoutManager(mContext, 12);
        GridSpaceItemDecoration decoration = new GridSpaceItemDecoration(mContext);
        int itemDecorationCount = mRecyclerView.getItemDecorationCount();
        if (itemDecorationCount > 0) {
            mRecyclerView.removeItemDecorationAt(0);
        }
        mRecyclerView.addItemDecoration(decoration);
        mRecyclerView.setLayoutManager(manager);
        adapter = new JoinGamePlayersMultiAdapter();
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return mRlRv.onTouchEvent(event);
            }
        });
    }

    private void initView() {
        mBtnGetCode = (TextView) mView.findViewById(R.id.btn_get_code);

        mLlGetCode = (LinearLayout) mView.findViewById(R.id.ll_get_code);
        mTvStatusLeft = (TextView) mView.findViewById(R.id.tv_status_left);
        mTvStatusLeftKuohao = (TextView) mView.findViewById(R.id.tv_status_left_kuohao);
        mTvStatusRiht = (TextView) mView.findViewById(R.id.tv_status_riht);

        mBanner = (Banner) mView.findViewById(R.id.banner);
        mTvLocationName = (TextView) mView.findViewById(R.id.tv_location_name);
        mTvDetailTime = (TextView) mView.findViewById(R.id.tv_detail_time);
        mTvDianpu = (TextView) mView.findViewById(R.id.tv_dianpu);
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.recycler_view);
        mTvFormat = (TextView) mView.findViewById(R.id.tv_format);
        mTvCost = (TextView) mView.findViewById(R.id.tv_cost);

        mTvPrize = (TextView) mView.findViewById(R.id.tv_prize);
        mTvTellphone = (TextView) mView.findViewById(R.id.tv_tellphone);
        mTvRemark = (TextView) mView.findViewById(R.id.tv_remark);
        mSmartLayout = (SmartRefreshLayout) mView.findViewById(R.id.smart_layout);
        mTvHuanjing = (TextView) mView.findViewById(R.id.tv_huanjing);
        mTvSaizhi = (TextView) mView.findViewById(R.id.tv_saizhi);
        mRlRv = (RelativeLayout) mView.findViewById(R.id.rl_rv);
    }

    @Override
    public void onResume() {
        super.onResume();
        MyApplication.refreeType = 0;
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageStart(getActivity(), "赛事报名中详情tab");
        }
        getDetailsId();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageEnd(getActivity(), "赛事报名中详情tab");
        }
    }

    //获取activity传值id
    private void getDetailsId() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            id = bundle.getString("id");
            String response = bundle.getString("response");
            //下拉刷新
            initFresh();
            fresh(id);
        }
    }

    private void initFresh() {
        mSmartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                fresh(id);
            }
        });
    }

    //刷新状态
    private void fresh(String id) {
        getGameStatusRole(id);
    }

    //获取赛事状态角色
    private void getGameStatusRole(String id) {
        showLoadingDialog("");
        PhoneLive.getGameStatusRole(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int idres) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            GameStatusRoleBean json = gson.fromJson(response, GameStatusRoleBean.class);
                            if (json != null) {
                                GameStatusRoleBean.DataBean data = json.getData();
                                if (data != null) {
                                    String role = data.getRole();
                                    int statusid = data.getStatusid();
                                    if (statusid != 2 && statusid != 8) {
                                        //发送eventbus粘性事件
                                        FragmentActivityMessageEvent event = new FragmentActivityMessageEvent();
                                        event.setMessage(1);
                                        event.setRole(role);
                                        event.setStatusId(statusid);
                                        EventBus.getDefault().postSticky(event);
                                    } else if (statusid == 2) {
                                        getDetailsSaiShiData(id);
                                    }
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    private void getDetailsSaiShiData(String id) {
        showLoadingDialog("");
        PhoneLive.getDetailsSaiShiData(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                mSmartLayout.finishRefresh(false);
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            mSmartLayout.finishRefresh(true);
                            SaiShiDetailsBean json = gson.fromJson(response, SaiShiDetailsBean.class);
                            if (json != null) {
                                SaiShiDetailsBean.DataBean data = json.getData();
                                if (data != null) {
                                    bottom = data.getBottom();
                                    info = data.getInfo();
                                    signup = data.isSignup();
                                    role = data.getRole();
                                    if (info != null) {
                                        status = info.getStatus();
                                        isOnlinePayment = info.getIsOnlinePayment();
                                        showButtonStyle(role, status, signup, bottom);
                                        List<String> banner = info.getBanner();
                                        if (bannerAdapter != null &&banner != null && banner.size() > 0) {
                                            mBanner.setVisibility(View.VISIBLE);
                                            bannerAdapter.setDatas(banner);
                                            bannerAdapter.notifyDataSetChanged();
                                        } else {
                                            mBanner.setVisibility(View.GONE);
                                        }
                                        initUi(info);
                                        SaiShiDetailsBean.DataBean.InfoBean.PlayerBean player = info.getPlayer();
                                        if (player != null) {
                                            List<String> player_images = player.getPlayer_images();
                                            String stringCount = BaseMethod.notNullDefaultValueNull(player.getSign_count() + "/" + player.getPlayer_count());
                                            if (player_images != null && player_images.size() > 10) {
                                                List<String> list = player_images.subList(0, 10);
                                                if (adapter != null)
                                                    adapter.setNewInstance(getPlayersMulDataBean(list, stringCount));
                                            } else {
                                                if (adapter != null)
                                                    adapter.setNewInstance(getPlayersMulDataBean(player_images, stringCount));
                                            }
                                        }
                                    }
                                }
                            }
                        } else mSmartLayout.finishRefresh(false);
                    } catch (JSONException e) {
                        mSmartLayout.finishRefresh(false);
                        e.printStackTrace();
                    }
                } else {
                    mSmartLayout.finishRefresh(false);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //选手
    private List<JoinPlayerBean> getPlayersMulDataBean(List<String> list, String stringCount) {
        List<JoinPlayerBean> arrayList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            arrayList.clear();
            for (int i = 0; i < list.size(); i++) {
                JoinPlayerBean bean = new JoinPlayerBean();
                bean.setItemType(0);
                bean.setString(list.get(i));
                arrayList.add(bean);
            }
            JoinPlayerBean bean = new JoinPlayerBean();
            bean.setItemType(1);
            bean.setString(stringCount);
            arrayList.add(bean);
        } else {
            arrayList.clear();
            JoinPlayerBean bean = new JoinPlayerBean();
            bean.setItemType(1);
            bean.setString(stringCount);
            arrayList.add(bean);
        }
        return arrayList;
    }

    //刷新ui
    private void initUi(SaiShiDetailsBean.DataBean.InfoBean info) {
        SaiShiDetailsBean.DataBean.InfoBean.BasicInfoBean basic_info = info.getBasic_info();
        SaiShiDetailsBean.DataBean.InfoBean.DescInfoBean desc_info = info.getDesc_info();
        SaiShiDetailsBean.DataBean.InfoBean.PlayerBean player = info.getPlayer();
        if (basic_info != null) {
            setText(mTvLocationName, BaseMethod.notNullDefaultValueNull(basic_info.getAddress_info()));
            setText(mTvDetailTime, BaseMethod.notNullDefaultValueNull(basic_info.getStart_at()));
            setText(mTvDianpu, BaseMethod.notNullDefaultValueNull(basic_info.getCustomer_name()));//主办方
        }
        setText(mTvHuanjing, getConditionName(info.getCondition()));
        setText(mTvFormat, getTypeName(info.getType()));
        if (desc_info != null) {
            setText(mTvSaizhi, BaseMethod.notNullDefaultValueNull(desc_info.getRule_display()));
            setText(mTvCost, BaseMethod.notNullDefaultValueNull(desc_info.getCost() + ""));
            setText(mTvTellphone, BaseMethod.notNullDefaultValueNull(desc_info.getContact()));
            setText(mTvPrize, BaseMethod.notNullDefaultValueNull(desc_info.getPrize_desc()));
            setText(mTvRemark, BaseMethod.notNullDefaultValueNull(desc_info.getRemarks()));
        }
    }

    private String getRuleName(int rule, int round, int wining) {
        //赛制1：瑞士轮 2：淘汰赛 3瑞士轮+淘汰赛 round轮 wining 出几强
        if (BaseMethod.notNull(rule + "") && rule == 1) {
            return getString(R.string.string_game_ruishilun) + round + getString(R.string.string_game_lun);
        }
        if (BaseMethod.notNull(rule + "") && rule == 2) {
            return getString(R.string.string_knock_out);
        }
        if (BaseMethod.notNull(rule + "") && rule == 3) {
            return getString(R.string.string_game_ruishilun) + round + getString(R.string.string_game_lun) + getString(R.string.string_game_chu) + wining + getString(R.string.string_game_qiang);
        }
        return "";
    }

    private String getConditionName(int condition) {
        //比赛环境（1：简体中文赛2：OCG）
        if (BaseMethod.notNull(condition + "") && condition == 1) {
            return getString(R.string.string_chinese_simple_environment);
        }
        if (BaseMethod.notNull(condition + "") && condition == 2) {
            return getString(R.string.string_ocg_environment);
        }
        return "";
    }

    private String getTypeName(int type) {
        //赛事类型 (1:娱乐赛2：积分赛)3：特殊赛4：巡回赛
        if (BaseMethod.notNull(type + "") && type == 1) {
            return getString(R.string.string_entertainment_race);
        }
        if (BaseMethod.notNull(type + "") && type == 2) {
            return getString(R.string.string_point_race);
        }
        if (BaseMethod.notNull(type + "") && type == 3) {
            return getString(R.string.string_teshu_race);
        }
        if (BaseMethod.notNull(type + "") && type == 4) {
            return getString(R.string.string_xunhui_race);
        }
        return "";
    }

    /**
     * 底部按钮
     * "customer":"商家",
     * "customerReferee":"商家+主裁判",
     * "notJoin":"没有参加",
     * "pReferee":"主裁判",
     * "player":"选手",
     * "referee":"裁判",
     * "visitor":"游客"
     * "pending":"审核中"
     */
    private void showButtonStyle(String role, int status, boolean signUp, SaiShiDetailsBean.BottomBean bottomBean) {
        boolean notJoin = BaseMethod.notNull(role) && role.equals("notJoin");
        boolean pReferee = BaseMethod.notNull(role) && role.equals("pReferee");
        boolean player = BaseMethod.notNull(role) && role.equals("player");
        boolean referee = BaseMethod.notNull(role) && role.equals("referee");
        boolean customer = BaseMethod.notNull(role) && role.equals("customer");
        boolean customerReferee = BaseMethod.notNull(role) && role.equals("customerReferee");
        boolean pending = BaseMethod.notNull(role) && role.equals("pending");
        if (bottomBean != null && bottomBean.getType() == 3 && (bottomBean.getAction() == 1 || bottomBean.getAction() == 2)) {   //3：倒计时样式
            UserGameList.DataBeanX.ResBean.DataBean.BottomBean.TitleBean title = bottomBean.getTitle();
            if (title != null) {
                mLlGetCode.setVisibility(View.VISIBLE);
                mTvStatusLeft.setVisibility(View.VISIBLE);
                mTvStatusLeftKuohao.setVisibility(View.VISIBLE);
                mTvStatusRiht.setVisibility(View.VISIBLE);
                mTvStatusLeft.setText(title.getText());
                mBtnGetCode.setText(SimpleUtils.time2String(title.getCountdown()));
                TimeCount(title.getCountdown());
            } else {
                mLlGetCode.setVisibility(View.GONE);
            }
        } else {
            mTvStatusLeft.setVisibility(View.GONE);
            mTvStatusLeftKuohao.setVisibility(View.GONE);
            mTvStatusRiht.setVisibility(View.GONE);
            if (customer || customerReferee || notJoin || player) {
                mLlGetCode.setVisibility(View.VISIBLE);
                if (customer || customerReferee) {
                    if (status != 2) {//显示开启比赛
                        mLlGetCode.setSelected(true);
                        if (status == 1)
                            mBtnGetCode.setText(getString(R.string.string_nt_immediately_start));
                        else {
                            mBtnGetCode.setText(getString(R.string.string_already_start));
                        }
                    } else {
                        mLlGetCode.setSelected(false);
                        mBtnGetCode.setText(getString(R.string.string_start_games));
                    }
                } else if (notJoin) {
                    mLlGetCode.setSelected(false);
                    mBtnGetCode.setText(getString(R.string.string_i_want_sign_up));
                } else {
                    mLlGetCode.setSelected(signUp);
                    mBtnGetCode.setText(signUp ? getString(R.string.string_exit_judge_game) : getString(R.string.string_i_want_sign_up));
                }
            } else {
                mLlGetCode.setVisibility(View.GONE);
            }
        }
    }

    public static BaoMingDetailsFragment newsInstance(String id, String response) {
        //创建 Bundle
        BaoMingDetailsFragment fragment = new BaoMingDetailsFragment();
        Bundle lBundle = new Bundle();
        lBundle.putString("id", id);
        lBundle.putString("response", response);
        fragment.setArguments(lBundle);
        return fragment;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
        if (mTimeCountDisposable != null) {
            mTimeCountDisposable.dispose();
        }
    }

    private Disposable mTimeCountDisposable;

    /**
     * 倒计时
     *
     * @param count
     */
    public void TimeCount(int count) {
        if (mTimeCountDisposable != null) {
            //取消上一次的订阅
            mTimeCountDisposable.dispose();
        }
        //0-count依次输出，延时0s执行，每1s发射一次。
        mTimeCountDisposable = Flowable.intervalRange(0, count, 0, 1, TimeUnit.SECONDS)
                .onBackpressureDrop()//过滤（抛弃）或者onBackpressurebuffer 缓存
                .observeOn(AndroidScheduler.mainThread())
                .doOnNext(aLong -> {
                    notifyTime();
                })
                .doOnComplete(() -> {
                    if (mTimeCountDisposable != null)
                        mTimeCountDisposable.dispose();
                })
                .subscribe();
    }

    private void notifyTime() {
        String string = mBtnGetCode.getText().toString();
        int string2Time = SimpleUtils.string2Time(string);
        if (string2Time <= 0) {
            mBtnGetCode.setText("00:00:00");
        } else {
            mBtnGetCode.setText(SimpleUtils.time2String(string2Time));
        }
    }
}
